package org.linlinjava.litemall.wx.annotation.support;

import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.wx.annotation.CurrentReferer;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class CurrentRefererHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    public static final String REFERER = "Referer";

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(String.class)
                && parameter.hasParameterAnnotation(CurrentReferer.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        String referer = request.getHeader(REFERER);
        if (StringUtils.isBlank(referer)) {
            return "";
        }

        return referer;
    }
}
